<template>
  <div class="app-container">
    <el-dialog title="期数日历" :visible.sync="calendarVisible" width="1200px" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-calendar v-model="myMonth">
        <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
        <template
          slot="dateCell"
          slot-scope="{date, data}"
        >
          <div v-if="showVolName(data.day)" style="height:70px;" @click="addVol(showVolData(data.day))">
            <div style="font-weight:bolder;color:blue;line-height:150%" v-html="data.day+'<br>第'+formatYear(showVolName(data.day))+'期'" />
            <!-- <div v-if="selectVols.indexOf(showVolName(data.day))!==-1">✔️</div> -->
          </div>
          <div v-else>{{ data.day }}</div>
        </template>
      </el-calendar>
    </el-dialog>

    <div v-if="!showList" class="filter-container">
      <div style="float:left;">
        <el-input v-model="listQuery.vol" placeholder="期数" style="margin-left: 10px;width: 100px;" class="filter-item" readonly @focus="showCalendar" />
        <el-button class="filter-item" style="margin-left: 10px;" icon="el-icon-date" @click="showCalendar">
          期数日历
        </el-button>
        <el-button class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilter">
          确定
        </el-button>
        <el-button class="filter-item" type="success" icon="el-icon-s-grid" style="margin-left: 10px;" @click="handleVolList">
          已生成期数
        </el-button>
      </div>
    </div>
    <template v-else>
      <el-button class="filter-item" icon="el-icon-back" style="margin-bottom:10px" @click="showList=false">
        返回
      </el-button>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <!-- <el-table-column v-if="roleEdit" type="selection" width="50" align="center" /> -->
        <el-table-column align="left" prop="classname" label="栏目" width="300px">
          <template slot-scope="scope">
            <template v-if="scope.row.parentId">
              ——{{ scope.row.classname }}
            </template>
            <template v-else>
              <b style="color:blue">{{ scope.row.classname }}</b>
            </template>
          </template>
        </el-table-column>
        <el-table-column align="left" prop="infoNum" label="信息数">
          <template slot-scope="scope">
            <template v-if="scope.row.parentId">
              {{ scope.row.infoNum }}
            </template>
            <template v-else>
              <b style="color:blue">{{ scope.row.infoNum }}</b>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-button v-if="!finish" type="primary" style="margin-top: 10px;" @click="collect(listQuery.volid)">确定生成</el-button>
      <el-button v-if="finish" type="primary" style="margin-top: 10px;" @click="collectBak(listQuery.volid)">生成文件</el-button>
      <el-button v-if="finish" type="success" style="margin-top: 10px;" @click="collectText(listQuery.volid)">生成纯文本</el-button>
      <el-button v-if="finish" class="filter-item" style="margin-top: 10px;" @click="handleVolList">
        已生成期数
      </el-button>
    </template>
  </div>
</template>

<script>
// import { fetchList } from '@/api/article'

const defaultForm = {
  memberCard: false,
  duration: 0,
  startDate: [],
  infoClass: '',
  realname: '',
  phone: '',
  phone2: '',
  idcard: '',
  volnum: '',
  isBold: '',
  isBlack: '',
  textb: '',
  content: '',
  title: '',
  // pics: [
  //   { src: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg', url: ['https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg'] },
  //   { src: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg', url: ['https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'] },
  //   { src: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg', url: ['https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'] }
  // ],
  price: '',
  // orderId: '',
  // dataCreateDatetime: '',
  // passedList: [],
  remark: '',
  vols: '',
  id: null
}
export default {
  name: 'ArticleList',
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        // this.$message({
        //   message: '请将表单填写完整',
        //   type: 'error'
        // })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      finish: false,
      allsum: 0,
      alltext: '',
      rules: {
        infoClass: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        phone: [{ validator: validateRequire }]
      },
      postForm: Object.assign({}, defaultForm),
      isEdit: false,
      monthVolList: [],
      selectVols: [],
      myMonth: null,
      calendarVisible: false,
      showList: false,
      limitTextNum: 65,
      loading: false,
      detail: {
        id: null,
        classId: null,
        realname: '',
        idcard: '',
        alltext: '',
        textNum: 0,
        textb: 0,
        vols: '',
        volnum: 0,
        remark: ''
      },
      previewVisible: false,
      infoClassList: [],
      unitName: '',
      roleName: '',
      cfajbh: '',
      showStep: [],
      showAddBtn: false,
      roleEdit: true,
      selection: false,
      dicListLoading: false,
      stopDicLoading: false,
      startDicLoading: false,
      submitLoading: false,
      classList: [],
      classForm: {
        parentClass: 14,
        label: ''
      },
      diclist: [],
      settingVisible: false,
      item: {},
      dialogtitle: '',
      dialogVisible: false,
      allDialogVisible: false,
      readOnly: false,
      timestamp: '',
      list: [
      ],
      list2: [],
      list3: [],
      total: 0,
      listLoading: true,
      listQuery: {
        status: 1,
        vol: '',
        infoClass: null,
        page: 1,
        limit: 20
      },
      Sortkey: '',
      Isace: '',
      multipleSelection: [],
      id: '',
      step: '',
      showThansferBtn: false,
      knowledgeVisible: false

    }
  },
  watch: {
    myMonth: {
      handler(val) {
        this.getVolsByDate()
      },
      immediate: true
    }
  },
  mounted() {
    this.getDefaultVol()
  },
  created() {
  },
  methods: {
    handleVolList() { this.$router.push({ name: 'volList' }) },
    collect(id) {
      this.$http.post('/api/busVol/updateCollectTime', { id: id, flag: 1 })
        .then(response => {
          if (response.data.success) {
            this.finish = true
            this.$message({
              message: '生成成功',
              type: 'success'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    collectBak(id) {
      window.open('/api/busInfo/getFilist?volId=' + id)
    },
    collectText(id) {
      // window.open(this.$http.defaults.baseURL + '/api/busInfo/getFilist?volId=' + id)
      window.open('/api/busInfo/getFilistText?volId=' + id)
    },
    addVol(vol) {
      console.log(vol)
      const year = new Date(vol.pubdate).getFullYear()
      const nowyear = new Date(vol.pubdate).getFullYear()
      let volname = parseInt(vol.name)
      if (year !== nowyear) {
        volname = (year - 2000) * 1000 + volname
      }
      this.listQuery.vol = volname
      this.listQuery.volid = vol.id
      this.calendarVisible = false
    },
    showVolName(date) {
      const item = this.monthVolList.find(item => item.pubdate === date)
      if (item) {
        const year = new Date(item.pubdate).getFullYear()
        let volname = parseInt(item.name)
        volname = (year - 2000) * 1000 + volname
        return volname
      }
    },
    showVolData(date) {
      const item = this.monthVolList.find(item => item.pubdate === date)
      if (item) {
        return item
      }
    },
    formatYear(str) {
      const year = parseInt('20' + str.toString().substring(0, 2))
      const nowYear = new Date().getFullYear()
      if (year === nowYear) {
        return parseInt(str.toString().substring(2, 5))
      } else {
        return str
      }
    },
    checkVols() {
      const checkVolList = [this.listQuery.vol]
      this.$http.post('/api/busVol/checkVolList', { volList: checkVolList, beforeDefault: false })
        .then(response => {
          if (response.data.result === false) {
            this.listQuery.vol = ''
            this.$message({
              message: '期数填写有误',
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    showCalendar() {
      // this.checkVols()
      this.calendarVisible = true
      this.getVolsByDate()
    },
    getVolsByDate() {
      const myDate = this.myMonth || new Date()
      const month = myDate.getMonth() + 1
      const year = myDate.getFullYear()
      this.$http
        .get('/api/busVol/getVolByDate?year=' + year + '&month=' + month)
        .then(response => {
          if (response.data.success === true) {
            this.monthVolList = response.data.result
          } else {
            this.$message({
              message: '获取失败3:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getDefaultVol() {
      this.$http
        .get('/api/busVol/getDefaultVol')
        .then(response => {
          if (response.data.success === true) {
            let defaultVol = response.data.result.name
            const pubdate = new Date(response.data.result.pubdate)
            const nowYear = new Date(response.data.result.pubdate).getFullYear()
            if (pubdate.getFullYear() !== nowYear) {
              defaultVol = (pubdate.getFullYear() - 2000) * 1000 + parseInt(defaultVol)
            }
            this.listQuery.vol = defaultVol
            this.listQuery.volid = response.data.result.id
          } else {
            this.$message({
              message: '获取失败4:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    handleFilter() {
      if (!this.listQuery.vol) {
        this.$message({
          message: '请填写期数',
          type: 'error'
        })
        return false
      }
      this.showList = true
      this.listQuery.page = 1
      this.getList()
    },
    getList() {
      this.listLoading = true
      this.$http
        .get('/api/busInfo/getClassStatByVolId?volId=' + this.listQuery.volid)
        .then(response => {
          this.listLoading = false
          if (response.data.success === true) {
            this.list = response.data.result
            this.allsum = 0
            this.list.filter(item => item.parentId).map(item => item.infoNum).forEach(val => {
              this.allsum += val
            })
            this.list.push({ classname: '总计', infoNum: this.allsum })
          } else {
            console.log('获取失败1:' + response.data.message)
            this.$message({
              message: '获取失败2:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.listLoading = false
        })
      // fetchList(this.listQuery).then(response => {
      //   this.list = response.data.items
      //   this.total = response.data.total
      //   this.listLoading = false
      // })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
<style>
.inputtable{
  background:#ccc;
  line-height: 150%;
}
</style>
